<template>
	<view class="view">
		<map v-if="showMain" :longitude="longitude" :latitude="latitude" :show-location="true" :polyline="polyLine">
			<navigator open-type="navigate" :url="'/subpages/rankingList/rankingList'" class="rankingList">排行榜</navigator>
			<!-- 跑步结果 -->
			<view v-if="!showRes">
				<view class="start-btn">
					<button @click="countDown">开始</button>
					<view @click="countDown" class="out"></view>
				</view>
			</view>
			<!-- 跑步结果 -->
			<view v-if="showRes">
				<view class="go-back" @click="goBack">
					<u-icon name="arrow-left" size="22" color="#80848f" /> 返回
				</view>
				<view class="runRes">
					<view>
						<text class="num">{{distance}}</text>
						<text>公里</text>
					</view>
					<view class="share rt" catch:tap="showShareMenu">
						<i-icon type="share" size="28" color="#fff" />
					</view>
					<view class="detail">
						<view class="time">
							<text>{{hours}}:{{minutes}}:{{secondes}}</text>
							<text>时长</text>
						</view>
						<view class="vraSpd">
							<text>{{avrSpeed}}</text>
							<text>平均配速</text>
						</view>
						<view class="heat">
							<text>{{heat}}</text>
							<text>热量(千卡)</text>
						</view>
					</view>
				</view>
			</view>
		</map>
		<!-- 正在跑步 -->
		<view v-if="!showMain" class="running">
			<view class="route">
				<text class="num">{{distance}}</text>
				<text>公里</text>
			</view>
			<view class="tmsp">
				<view class="time lf">
					<text>{{hours}}:{{minutes}}:{{secondes}}</text>
					<text>时长</text>
				</view>
				<text class="text">|</text>
				<view class="avrSpeed rt">
					<text>{{speed}}</text>
					<text>配速</text>
				</view>
			</view>
			<view class="run-btn">
				<button class="lf-btn" @click="pauseRun">{{pause}}</button>
				<button class="rt-btn" @click="endRun">结束</button>
			</view>
		</view>
	</view>
</template>

<script>
	import { mapState } from 'vuex'
	import { upSportMes } from '@/config/api.js'
	var format = require('@/util/util.js')
	var QQMapWX = require('@/libs/qqmap-wx-jssdk.js')
	var qqmapsdk
	let timer = null
	let points = []
	let point = [] // 记录位置信息
	let count = 0 // 
	let spdMax = 0
	let spdMin = 0
	let distanceSum = 0
	let params = {}
	//进行经纬度转换为距离的计算
	function Rad(d) {
		//经纬度转换成三角函数中度分表形式。
		return d * Math.PI / 180.0
	}
	//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度
	function distance(lat1, lng1, lat2, lng2) {
		let radLat1 = Rad(lat1)
		let radLat2 = Rad(lat2)
		let a = radLat1 - radLat2
		let b = Rad(lng1) - Rad(lng2)
		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) +
			Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
		s = s * 6378.137 // EARTH_RADIUS;
		//输出为公里
		s = Math.round(s * 10000) / 10000
		// s = Number(s.toFixed(2));
		distanceSum += s
		return distanceSum
	}
	// 比较最大最小速度
	function spdCheck(speed) {
		spdMax = speed > spdMax ? speed : spdMax
		spdMin = speed < spdMin ? speed : spdMin
	}
	export default {
		data() {
			return {
				showMain: true, // 是否显示首页
				showRes: false, // 是否显示跑步页面
				longitude: '',
				latitude: '',
				distance: '0.00', // 距离
				secondes: '00', // 秒
				minutes: '00', // 分钟
				hours: '00', // 小时
				speed: '--', // 配速
				maxSpeed: '--', // 最快速度
				minSpeed: '--', // 最慢速度
				avrSpeed: '--', // 平均速
				heat: '0', // 热量
				pause: '暂停',
				starOne: false, // 是否开启了主页面的位置监听
				polyLine: [], //地图画线
				// stopCount: 0, //暂停计数
			}
		},
		onLoad() {
			// 实例化API核心类
			qqmapsdk = new QQMapWX({ key: 'ZYQBZ-7KBCP-YPDDQ-LG7ER-2VIB6-PKBXK' })
			// 调用接口
			this.getLocation()
		},
		computed: { ...mapState(['userinfo', 'loginState']) },
		methods: {
			// 初始定位
			getLocation() { // 初始化页面时需要获取一次定位权限
				const that = this
				wx.startLocationUpdateBackground({
					success(res) { // 成功
						console.log('开启后台定位', res)
					},
					fail(res) {
						console.log('开启后台定位失败', res)
					}
				})
				wx.getLocation({
					type: 'gcj02',
					accuracy: 10,
					success: res => {
						console.log(res)
						console.log('11latitude=' + res.latitude + ',11longitude=' + res.longitude)
						that.latitude = res.latitude
						that.longitude = res.longitude
					},
					fail: res => {
						console.log('开启定位失败', res)
					}
				})
			},
			// 获取经纬度变化
			getLocationChange() {
				const that = this
				//开启后台定位
				wx.startLocationUpdateBackground({
					success(res) { // 成功
						console.log('开启后台定位', res)
						wx.onLocationChange(res => { // 开启持续更新
							console.log('22latitude=' + res.latitude + ',22longitude=' + res.longitude)
							that.latitude = res.latitude
							that.longitude = res.longitude
							that.speed = format.formatSpeed(res.speed) // 获取速度
							const speedArr_i = res.speed <= 0 ? 0 : res.speed // 判断速度是否发生变化，变化了就记录
							spdCheck(speedArr_i) // 比较最大最小速度
							point.push({ // 将位置数据记录到数组中
								latitude: res.latitude,
								longitude: res.longitude
							})
						})
					},
					fail(res) {
						console.log('开启后台定位失败', res)
					}
				})
			},
			// 跑步划线
			drawline() {
				for (var i = 0; i < points.length; i++) {
					this.polyLine.push({
						points: points[i],
						color: '#48F90D',
						width: 5,
					})
				}
				// this.polyLine = [{
				// 	points: point,
				// 	color: '#48F90D',
				// 	width: 5,
				// }]
			},
			// 点击开始
			countDown() {
				if (!this.loginState) {
					uni.showToast({
						icon: 'none',
						title: '请先登录'
					})
					return
				}
				let battery = wx.getBatteryInfoSync()
				if (battery.level < 20) {
					uni.showModal({
						title: '电量过低',
						showCancel: true,
						cancelText: '回家充电',
						confirmText: '继续',
						content: '当前电量较低(' + battery.level + '%)，GPS定位会不准确，本次运动可能无法完整记录',
						success: res => {
							if (res.confirm) {
								this.countDownStart() // 开始倒计时
							} else if (res.cancel) {
								console.log('用户点击取消')
							}
						}
					})
				} else {
					this.countDownStart() // 开始倒计时
				}
				this.showMain = false
			},
			// 开始倒计时
			async countDownStart() {
				const audioctx = wx.createInnerAudioContext() // 创建音乐播放对象
				audioctx.src = '@/voice/countDown.mp3' // 获取音频地址
				audioctx.autoplay = true // 自动播放
				this.showMain = false // 切换页面
				let second = 3
				while (second > 0) { // 倒计时
					second !== 3 && (await new Promise(resolve => setTimeout(resolve, 1000)))
					await uni.showLoading({ title: `倒计时 ${second} 秒`, })
					second--
				}
				if (second === 0) {
					setTimeout(() => uni.hideLoading(), 1000)
					clearTimeout(timer)
					this.initData() // 初始化数据
					this.startInterface()
					this.startRun()
				}
			},
			// 调用开始接口
			startInterface() {
				wx.setKeepScreenOn({ //设置屏幕常亮-开始
					keepScreenOn: true
				})
			},
			// 开始运动
			startRun() {
				let that = this
				this.getLocationChange()
				timer = setInterval(that.repeat, 1000)
			},
			// 暂停运动
			pauseRun() {
				let that = this
				if (this.pause === '暂停') {
					this.stopLocationUpdate()
					points.push(point) // 把记录的坐标记录到points中
					// this.stopCount = points.length - 1 // 画线数组加下标加一
					point = [] // 清空
					clearInterval(timer)
					timer = null
					this.pause = '继续'
				} else {
					this.startRun()
					this.pause = '暂停'
				}
			},
			// 结束运动按钮
			async endRun() {
				const that = this
				//设置屏幕常亮-结束
				wx.setKeepScreenOn({ keepScreenOn: false })
				clearInterval(timer)
				timer = null
				let spdAvr = 0
				const endTime = format.formatTime(new Date())
				const runTime = Math.ceil(count / 60)
				if (that.pause === '暂停') { // 如果不是暂停的时候点击结束运动，把最后的路线添加到points中
					points.push(point)
					// this.stopCount = points.length - 1 // 画线数组加下标加一
				}
				this.showMain = true
				this.showRes = true
				spdAvr = distanceSum ? (distanceSum * 1000) / count : 0
				this.distance = (+this.getDistance()).toFixed(2)
				this.avrSpeed = format.formatSpeed(spdAvr)
				this.maxSpeed = spdMax
				this.minSpeed = spdMin
				// 热量 =体重（kg）* 距离（km）* 运动系数（k） 跑步：k=1.036
				this.heat = parseInt(55 * this.distance * 1.036)
				this.drawline()
				this.stopLocationUpdate()
				uni.showLoading({
					title: '上传数据中',
					mask: true
				})
				const res = await upSportMes({
					userId: this.userinfo.pid,
					distance: this.distance,
					avgPace: this.avrSpeed,
					runTime: `${this.hours}:${this.minutes}:${this.secondes}`,
					calorie: this.heat,
					endTime: uni.$u.timeFormat(new Date().valueOf(), 'yyyy/mm/dd hh:MM:ss')
				})
				setTimeout(() => {
					uni.hideLoading()
				}, 1000)
			},
			// 暂停位置更新
			stopLocationUpdate() {
				// 取消监听位置变化
				wx.offLocationChange()
				// 关闭监听位置实时变化，前后台都将收不到位置信息
				wx.stopLocationUpdate({
					success(res) {
						console.log('结束监听成功：', res)
					},
					fail(err) {
						console.log('结束监听失败：', err)
					}
				})
			},
			// 记录跑步数据,整公里震动提醒
			repeat() {
				let that = this
				this.getTime()
				let distance = (+that.getDistance()).toFixed(2)
				this.distance = distance
				// 整公里提醒
				if (!this._shake) this._shake = 1
				if (distance - this._shake > 0) {
					this._shake = parseInt(distance) + 1
					wx.vibrateLong()
				}
			},
			// 秒表计时器
			getTime() {
				count++
				this.secondes = format.formatNumber(count % 60)
				this.minutes = format.formatNumber(parseInt(count / 60) % 60)
				this.hours = format.formatNumber(parseInt(count / 60 / 60))
			},
			// 显示路程
			getDistance() {
				if (point.length <= 1) {
					return this.distance
				} else {
					return distance(point[point.length - 2].latitude, point[point.length - 2].longitude, point[point
						.length - 1].latitude, point[point.length - 1].longitude)
				}
			},
			// 返回主页
			goBack() {
				this.initData()
			},
			// 初始化数据
			initData() {
				points = []
				point = []
				count = 0
				distanceSum = 0
				spdMin = 0
				spdMax = 0
				params = {}
				// this.getlocation();
				this.showRes = false
				this.secondes = '00'
				this.minutes = '00'
				this.hours = '00'
				this.distance = '0.00'
				this.maxSpeed = '--'
				this.minSpeed = '--'
				this.avrSpeed = '--'
				this.heat = '0'
				this.polyLine = []
				// this.stopCount = 0
				// this.nonImg = null
				// this.monImg = null
				// this.isShowShareMenu = false
			},
		}
	}
</script>

<style lang="scss" scoped>
	uni-page-body,
	html,
	body {
		height: 100%;
		margin: 0;
	}
	button {
		padding: 0;
		margin: 0;
	}
	map {
		width: 750upx;
		height: 100vh;
	}
	/* 排行榜 */
	.rankingList{
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		color: #80848f;
	}
	.view {
		width: 100%;
		height: 100vh;
		position: relative;
		/* 主页面 */
		.start-btn {
			position: absolute;
			bottom: -1vh;
			/* background: #fff; */
			background: linear-gradient(to top, #63b7af, transparent);
			/* line-height: 350rpx; */
			height: 350rpx;
			width: 100%;
			/* border-radius: 50%; */
			text-align: center;
			font-size: 50rpx;
			font-weight: bold;
			/* 开始按钮动画效果 */
			@-webkit-keyframes fx-plyr-play-button {
				0% {
					-webkit-transform: scale(0.667);
					transform: scale(0.667);
					opacity: 0.5;
				}
				to {
					opacity: 0
				}
			}
			@keyframes fx-plyr-play-button {
				0% {
					-webkit-transform: scale(0.667);
					transform: scale(0.667);
					opacity: 0.5;
				}
				to {
					opacity: 0
				}
			}
			button {
				margin: 0 auto;
				height: 200rpx;
				width: 200rpx;
				line-height: 200rpx;
				border-radius: 50%;
				/* background: #78B078; */
				background: linear-gradient(to left top, #63b7af, #abf0e9);
				color: #fff;
				font-weight: bold;
			}
			.out {
				margin: -250rpx auto;
				width: 300rpx;
				height: 300rpx;
				-webkit-animation: fx-plyr-play-button 1s ease-out infinite;
				animation: fx-plyr-play-button 1s ease-out infinite;
				border: 5px solid #fff;
				border-radius: 50%;
				-webkit-box-shadow: 0 0 5px #fff;
				box-shadow: 0 0 5px #fff;
				-webkit-box-sizing: border-box;
				box-sizing: border-box;
				content: "";
			}
		}
		/* 正在跑步开始 */
		.running {
			height: 100%;
			background: linear-gradient(to top, #63b7af, transparent);
			text-align: center;
			overflow: hidden;
			.route {
				color: #ee8572;
				margin: 100rpx 0;
				.num {
					font-size: 200rpx;
					display: block;
					/* font-family: fantasy; */
				}
			}
			.text {
				color: #fff;
				line-height: 50rpx;
			}
			.tmsp {
				overflow: hidden;
				width: 350rpx;
				margin: 0 auto;
				.lf {
					float: left
				}
				.rt {
					float: right;
				}
			}
			.time,
			.avrSpeed {
				text {
					color: #999;
					display: block;
				}
			}
			.run-btn {
				position: fixed;
				bottom: 0;
				width: 100%;
				height: 300rpx
			}
			.run-btn {
				button {
					display: inline-block;
					border-radius: 50%;
					height: 150rpx;
					width: 150rpx;
					margin: 0 40rpx;
					line-height: 150rpx;
					color: #fff;
				}
				.lf-btn {
					background: #ffe0ac;
				}
				.rt-btn {
					background: #ee8572;
				}
			}
		}
		/* 跑步结束 */
		.go-back {
			color: #80848f;
			/* background: #fff; */
			width: 150rpx;
			line-height: 80rpx;
			position: relative;
			z-index: 1000;
			display: flex;
		}
		.runRes {
			width: 96vw;
			height: 300rpx;
			margin: 0 auto;
			background: linear-gradient(to left top, #63b7af, #abf0e9);
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			margin: auto;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			color: #fff;
			text-align: center;
			overflow: hidden;
		}
		.runRes .num {
			display: block;
			font-size: 80rpx;
		}
		.runRes .detail {
			overflow: hidden;
			display: flex;
			justify-content: space-between;
			padding: 20rpx 30rpx;
		}
		.runRes .detail text {
			display: block;
		}
		.runRes .share {
			position: absolute;
			right: 30rpx;
			top: 20rpx;
		}
	}
</style>